package com.coldworks.coldjoke.task;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coldworks.base.manager.BaseBitmapManager;
import com.coldworks.base.manager.BaseDisplayManager;

public class AsyncImgLoader {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	private static AsyncImgLoader instance = null;

	public static AsyncImgLoader getInstance() {
		if (instance == null) {
			synchronized (AsyncImgLoader.class) {
				if (instance == null) {
					instance = new AsyncImgLoader();
				}
			}
		}
		return instance;
	}

	private AsyncImgLoader() {
		imageCache = new HashMap<String, SoftReference<Bitmap>>();
	}

	private HashMap<String, SoftReference<Bitmap>> imageCache;

	@SuppressLint("HandlerLeak")
	public Bitmap loadDrawableByUrl(final Context context,
			final String imageUrl, final ImageView imageView,
			final UrlImageCallback imageCallback, final File folder,
			final boolean isNeedThumbnail) {
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
			Bitmap bitmap = softReference.get();
			if (bitmap != null) {
				return bitmap;
			}
		}
		final Handler urlHandler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Bitmap) message.obj, imageView,
						imageUrl);
			}
		};
		new Thread() {
			@Override
			public void run() {
				Bitmap bitmap = null;
				try {
					String fileName = BaseBitmapManager.getInstance()
							.getFileNameByUrl(imageUrl);
					if (fileName == null) {
						return;
					}
					File file = new File(folder + File.separator + fileName);
					if (file == null || !file.exists()) {
						boolean succ = BaseBitmapManager.getInstance()
								.downBitmapByUrl(context, imageUrl, file);
						if (!succ) {
							return;
						}
					}
					if (isNeedThumbnail) {
						bitmap = BaseBitmapManager.getInstance()
								.getThumbnailByPath(context,
										file.getAbsolutePath(), 96, 96);
					} else {
						bitmap = BaseBitmapManager.getInstance()
								.getBitmapByFile(
										context,
										file,
										BaseBitmapManager.getInstance()
												.getOptions(file),
										BaseDisplayManager.getInstance()
												.getDisplayWidth(context),
										BaseDisplayManager.getInstance()
												.getDisplayHeight(context),
										true);
					}
				} catch (Exception e) {
					log.error("", e);
					return;
				}
				if (bitmap == null) {
					return;
				}
				imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));
				Message message = urlHandler.obtainMessage(0, bitmap);
				urlHandler.sendMessage(message);
			}
		}.start();
		return null;
	}

	@SuppressLint("HandlerLeak")
	public Bitmap loadDrawableByPath(final Context context,
			final String imagePath, final ImageView imageView,
			final FileImageCallback imageCallback, final boolean isNeedThumbnail) {
		if (imageCache.containsKey(imagePath)) {
			SoftReference<Bitmap> softReference = imageCache.get(imagePath);
			Bitmap bitmap = softReference.get();
			if (bitmap != null) {
				log.info("load bitmap from cache");
				return bitmap;
			}
		}
		final Handler pathHandler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Bitmap) message.obj, imageView,
						imagePath);
			}
		};
		new Thread() {
			@Override
			public void run() {
				Bitmap bitmap = null;
				try {
					File file = new File(imagePath);
					if (file == null || !file.exists()) {
						log.warn("no such file");
						return;
					}
					if (isNeedThumbnail) {
						bitmap = BaseBitmapManager.getInstance()
								.getThumbnailByPath(context,
										file.getAbsolutePath(), 96, 96);
					} else {
						bitmap = BaseBitmapManager.getInstance()
								.getBitmapByFile(
										context,
										file,
										BaseBitmapManager.getInstance()
												.getOptions(file),
										BaseDisplayManager.getInstance()
												.getDisplayWidth(context),
										BaseDisplayManager.getInstance()
												.getDisplayHeight(context),
										true);
					}
				} catch (Exception e) {
					log.error("", e);
					return;
				}
				if (bitmap == null) {
					log.warn("load null from file");
					return;
				}
				imageCache.put(imagePath, new SoftReference<Bitmap>(bitmap));
				Message message = pathHandler.obtainMessage(0, bitmap);
				pathHandler.sendMessage(message);
			}
		}.start();
		return null;
	}

	public interface UrlImageCallback {
		public void imageLoaded(Bitmap imageDrawable, ImageView imageView,
				String imageUrl);
	}

	public interface FileImageCallback {
		public void imageLoaded(Bitmap imageDrawable, ImageView imageView,
				String imagePath);
	}
}
